<template>
  <div style="width:600px;margin: 0 auto">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>密码修改</span>
        </div>
      </template>
      <el-form :model="formData" 
               :rules="rules"
               ref="formRef"
               label-width="100px">
        <el-form-item prop="oldPassword" label="旧密码">
          <el-input type="password"
                    v-model="formData.oldPassword"
                    auto-complete="off"
                    placeholder="请输入旧密码">
          </el-input>
        </el-form-item>
        <el-form-item prop="newPassword" label="新密码">
          <el-input type="password"
                    v-model="formData.newPassword"
                    auto-complete="off"
                    placeholder="请输入新密码">
          </el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword" label="确认密码">
          <el-input type="password"
                    v-model="formData.confirmPassword"
                    auto-complete="off"
                    placeholder="请再次输入新密码">
          </el-input>
        </el-form-item>
        <el-form-item style="width:100%;">
          <el-button type="primary" style="width:100px;" @click="handleSubmit">修改密码</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import http from "@/utils/http.js";
import { ref } from "vue";
import { ElMessage } from "element-plus";
import router from "@/router/index.js";
import tools from "@/utils/tools.js";
import * as path from "node:path";

const formRef = ref(null);
const formData = ref({
  id: tools.parseToken()?.id,
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'));
  } else {
    if (formData.value.confirmPassword !== '') {
      formRef.value?.validateField('confirmPassword');
    }
    callback();
  }
};

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== formData.value.newPassword) {
    callback(new Error('两次输入密码不一致!'));
  } else {
    callback();
  }
};

const rules = {
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, validator: validatePass, trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePass2, trigger: 'blur' }
  ]
};

function handleSubmit() {
  formRef.value?.validate((valid) => {
    if (!valid) {
      return;
    }
    
    const data = {
      id: formData.value.id,
      oldPassword: formData.value.oldPassword,
      password: formData.value.newPassword
    };

    http.post('/api/admin/updatePassword', data).then(res => {
    if (!res) {
        return;
    }
      // 清除所有本地存储的数据
      localStorage.clear();
      sessionStorage.clear();
      // 清除所有 cookie
      document.cookie.split(";").forEach(function(c) { 
        document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); 
      });
      
    ElMessage({
        message: '修改成功，请重新登录',
      type: 'success'
    });

      // 使用 replace 而不是 push，防止返回到修改密码页面
      router.replace('/login').then(() => {
        // 在路由跳转完成后刷新页面
        window.location.reload();
      });
    });
  });
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
